package com.google.code.dajly.converter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;


/***Convertitore da RSS a RSS esteso
 * @author stefano pigozzi*/
public class Converter {
	
	static public void main(String... args) {
		
		Converter conv = new Converter();
		
		for(String a : args){
			if(a.equals("-v") || a.equals("--verbose"))
				conv._verbose = true;
			
			if(a.startsWith("loc="))
				conv._loc = a.substring(4).replace(',', ';').replaceAll("\"", "");
			
			if(a.startsWith("bus="))
				conv._bus = a.substring(4).replace(',', ';').replaceAll("\"", "");
			
			if(a.startsWith("input="))
				conv._input = a.substring(6).replaceAll("\"", "");
			
			if(a.startsWith("output="))
				conv._output = a.substring(7).replaceAll("\"", "");
						
		}
		
		conv.convert();
		
	}
	
	private Document doc;
	
	private InputStream XMLFILE;
	private boolean _verbose;
	private String _output = "out.xml";
	private String _input = "http://www.corriere.it/rss/ultimora.xml";
	private String _loc = "LocA;LocB;LocC";
	private String _bus = "BusA;BusB";
	
	public void convert(){
		
		try {
			this.XMLFILE = new URL(_input).openStream();
		} catch (MalformedURLException e1) {
			System.err.println("ERROR!: MALFORMED URL");
		} catch (IOException e1) {
			System.err.println("ERROR!: Can't open stream to XML file!");
		}
		
        SAXBuilder builder = new SAXBuilder();
		try {
			doc = builder.build(XMLFILE);
			Namespace ns = Namespace.getNamespace("dajly", 
			"http://code.google.com/p/dajly/wiki/namespace");
			
			doc.getRootElement().addNamespaceDeclaration(ns); // metto il nostro namespace!
			
			Element channel = doc.getRootElement().getChild("channel");
			
			Element location = new Element("location",ns);
			location.addContent(this._loc);
			channel.addContent(location);
			
			Element business = new Element("business",ns);
			business.addContent(this._bus);
			channel.addContent(business);
						
			
			XMLOutputter fmt = new XMLOutputter();
			if(_verbose)
				fmt.output(doc, System.out);
			fmt.output(doc, new FileWriter(new File(_output)));

		} catch (JDOMException e) {
		} catch (IOException e) {
		}
		
		
		
	}

	
}
